import ProTable from '@ant-design/pro-table';
import { Form } from '@ant-design/compatible';
import { Button, message, Icon, DatePicker, Input, Select, Modal } from 'antd';
import React, { useState, useRef, useEffect, useCallback } from 'react';
import '@ant-design/compatible/assets/index.css';
import { airlineTable, airlineTableExport, queryCityInfo} from '../service';
import { useRequest } from '@umijs/hooks';

import styles from './index.less';
import { formatFlightNo, controlTableHeight } from '@/utils/pagesGeneralMethods'; // 页面通用方法

import moment from 'moment';
import AuthComponent from '@/components/Authorized/AuthComponent';

const { Option } = Select;
const { confirm } = Modal
let hiddenData = null

const DetailTable = () => {
  const { data: selectData } = useRequest(queryCityInfo);

  // 切换清空搜索
  useEffect(() => {
    hiddenData = null
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
const [isCollapse, controlC] = useState(true); //搜索面板是否折叠
 
  const actionRef = useRef();
  const ref = useRef();

  const [inited, setInited] = useState(true)

  const [searchParams, setSearchParams] = useState('')

  const [exportFlag, handleExportFlag] = useState('')

    /**
   * 导出
   */
  const handleExport = () => {
    if (!exportFlag){
      message.error('表格数据为空')
      return false
    }
    const hide = message.loading('正在导出');
    let res = airlineTableExport(searchParams).then(res=>{
      let blob = new Blob([res], {
        type: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      })
      let elink = document.createElement('a')
      let time=moment(Date.now()).format('YYYY-MM-DD HH:mm:ss')
      elink.download = '航线统计报表'+time+'.xls'
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      document.body.removeChild(elink)
      hide();
      message.success('导出成功');
    }).catch(err => {
      console.log(err)
    });
  }

  // 搜索
  const beforeSearchSubmit = useCallback(params =>{
    params['flightDateBegin'] = params.flightDateBegin ? params.flightDateBegin.format('YYYY-MM-DD') : '';
    params['flightDateEnd'] = params.flightDateEnd ? params.flightDateEnd.format('YYYY-MM-DD') : '';
    params['optDateBegin'] = params.optDateBegin ? params.optDateBegin.format('YYYY-MM-DD') : '';
    params['optDateEnd'] = params.optDateEnd ? params.optDateEnd.format('YYYY-MM-DD') : '';
    if (!isCollapse) {
      setSearchParams(params)
      return params
    } else {
      if (event.target.querySelector('span') && event.target.querySelector('span').innerText === '查 询') {
        if (Object.keys(params).indexOf('flightDateBegin') === -1) {
          params.flightDateBegin = ''
        }
        if (Object.keys(params).indexOf('flightDateEnd') === -1) {
          params.flightDateEnd = ''
        }

        setSearchParams({...hiddenData, ...params})
        return { ...hiddenData, ...params}
        
      } else if (event.target.querySelector('span') && event.target.querySelector('span').innerText === '重 置') {
        ref.current.setFieldsValue({
          flightDateBegin: moment(),
          flightDateEnd: moment()
        })
        hiddenData = null
        setSearchParams(params)
        return params
      }
    }
  }, [isCollapse]);

  const columns = [
    {
      title: '航班起始日期',
      dataIndex: 'flightDateBegin',
      order: 9,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '航班结束日期',
      dataIndex: 'flightDateEnd',
      order:8,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '操作起始日期',
      dataIndex: 'optDateBegin',
      order:4,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}r
            {...rest}
          />
        );
      },
    },
    {
      title: '操作结束日期',
      dataIndex: 'optDateEnd',
      order:3,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '航班号',
      width:90,
      order: 7,
      dataIndex: 'flightNo',
      renderFormItem: (_, { type, defaultRender, ...rest }) => {
        return <Input 
          {...rest}
          onChange= {e => {
            e.target.value = formatFlightNo(e.target.value);
            rest.onChange(e.target.value)
          }}
          allowClear maxLength={6} placeholder="3U" />;
      }
    },
    {
      title: '起始航站',
      dataIndex: 'org',
      width: 120,
      order: 6,
      initialValue: '', //缺个默认接口服务航站
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
    },
    {
      title: '到达航站',
      dataIndex: 'dst',
      width: 120,
      order: 5,
      initialValue: '', //缺个默认接口服务航站
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
    },
    {
      title: '航班性质',
      dataIndex: 'flightType',
      width:100,
      order:1,
      filters: false,
      // valueEnum: {
      //   '1': '国内',
      //   '2': '国际',
      // },
      valueEnum: {
        'D': '国内',
        'I': '国际',
      },
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            mode="multiple"
            allowClear={true}
            placeholder="请选择"
          >
            <Option key='D'>国内</Option>
            <Option key='I'>国际</Option>
          </Select>
        );
      },
    },
    {
      title: '次数',
      dataIndex: 'count',
      hideInSearch: true,
      width: 90,
    },
  ];


  return (
    <div>
      <ProTable
        className={styles.vipPaxCharts}
        formRef={ref}
        options={{density: false, fullScreen:true, reload:false, setting:true}}
        scroll={{ x: 1300, y: controlTableHeight(isCollapse, 360, 470) }}
        size='small'
        search={{
          onCollapse:val => {
            controlC(val);
            // if (!val && hiddenData) {
            //   ref.current.setFieldsValue({
            //     flightNumber: hiddenData.flightNumber,
            //   })
            // } else {
            //   hiddenData = ref.current.getFieldsValue()
            // }
          },
          span: { //设置排列方式
            xs: 24,
            sm: 24,
            md: 6,
            lg: 6,
            xl: 6,
            xxl: 6,
          }
        }}
        headerTitle={
          <div>
            <span style={{ paddingRight: 10, fontWeight: "bold", color: "#000" }}>航线统计表</span>
          </div>
        }
        toolBarRender={(action, { selectedRows }) => [
          <AuthComponent authCode="vipRoom.airlineCharts.export">
            <Button icon="download" type="primary"  onClick={handleExport}>
              导出
            </Button>
          </AuthComponent>
        ]}
        actionRef={actionRef}
        rowKey="id"
        rowSelection={false}
        pagination={{
          showSizeChanger: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`
        }}
        columns={columns}
        beforeSearchSubmit={beforeSearchSubmit}
        postData={data => {
          if (data.length === 0) {
            handleExportFlag(false)
          } else {
            handleExportFlag(true)
          }
          return data
        }}
        request={params => {
          if (!params['flightDateBegin'] && !params['flightDateEnd']) {
            params['flightDateBegin'] = moment().format('YYYY-MM-DD');
            params['flightDateEnd'] = moment().format('YYYY-MM-DD');
            ref.current.setFieldsValue({
              flightDateBegin: moment()
            })
            ref.current.setFieldsValue({
              flightDateEnd: moment()
            })
          }
          params.flightType = params.flightType && params.flightType.join(',')

          setSearchParams(params)
          return airlineTable(params)
        }}
      />
    </div>
  );
};

export default Form.create()(DetailTable);
